package com.foodorder.repository;

import com.foodorder.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 分类数据访问层
 */
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long>, JpaSpecificationExecutor<Category> {
    
    /**
     * 根据店铺ID查找分类
     */
    List<Category> findByStoreId(Long storeId);
    
    /**
     * 根据店铺ID和启用状态查找分类
     */
    List<Category> findByStoreIdAndEnabled(Long storeId, Boolean enabled);
    
    /**
     * 查找所有激活的分类
     */
    List<Category> findByEnabledOrderBySortOrderAsc(Boolean enabled);
    
    /**
     * 根据分类名称查找
     */
    List<Category> findByNameContaining(String name);
    
    /**
     * 查找有商品的分类
     */
    @Query("SELECT DISTINCT c FROM Category c WHERE c.id IN " +
           "(SELECT DISTINCT p.categoryId FROM Product p WHERE p.status = 'AVAILABLE') " +
           "AND c.enabled = :enabled ORDER BY c.sortOrder ASC")
    List<Category> findCategoriesWithProducts(@Param("enabled") Boolean enabled);
    
    /**
     * 统计分类下的商品数量
     */
    @Query("SELECT COUNT(p) FROM Product p WHERE p.categoryId = :categoryId AND p.status = com.foodorder.entity.Product$ProductStatus.AVAILABLE")
    long countProductsByCategoryId(@Param("categoryId") Long categoryId);
    
    /**
     * 根据店铺ID和启用状态查找分类（按排序顺序）
     */
    List<Category> findByStoreIdAndEnabledOrderBySortOrderAsc(Long storeId, Boolean enabled);
}